class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def subtreeWithAllDeepest(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        d = {}
        stack = [root]
        while True:
            next_stack = []
            for node in stack:
                if node.left:
                    next_stack.append(node.left)
                    d[node.left] = node
                if node.right:
                    next_stack.append(node.right)
                    d[node.right] = node
            if not next_stack:
                break
            else:
                stack = next_stack
        while len(stack) != 1:
            next_stack = set()
            for node in stack:
                next_stack.add(d[node])
            stack = next_stack
        return stack.pop()

